package tests;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.studerb.model.Header;
import com.studerb.model.NewsGroup;
import com.studerb.service.interfaces.IHeaderService;
import com.studerb.service.interfaces.INewsGroupService;

public class TestHeaderThreads {

	private static Logger logger = Logger.getLogger("TESTS");
	private static ClassPathXmlApplicationContext springAppContext;
	private static IHeaderService headerService;
	private static INewsGroupService newsGroupService;
	private static String groupName = "1.binaries.pictures.erotica";

	private static NewsGroup newsGroup;

	public static void main(String args[]) {
		com.jidesoft.utils.Lm.verifyLicense("Bill Studer", "Gnusbin", "GUPxWo:0hpUtR3u94.K90:R7sPr.VCv2");
		logger.debug("Starting");
		try {
			setUpSpring();
			newsGroup = newsGroupService.getByGroupName(groupName);
			headerService.deleteAllPosts(newsGroup);
			processHeaders();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			springAppContext.close();
		}

		System.exit(0);
	}

	private static void processHeaders() throws IOException {
		String fileName = "classpath:tests/headers.txt";
		File headerFile = springAppContext.getResource(fileName).getFile();
		BufferedReader reader = new BufferedReader(new FileReader(headerFile));
		String current = null;
		int count = 0;
		while ((current = reader.readLine()) != null) {
			Header header = Header.createHeader(current, newsGroup);
			if (header != null && ++count % 100 == 0) {
				logger.debug(count + ": " + header);
			}

		}
	}

	private static void setUpSpring() {
		logger.debug("Starting Spring Application Context");
		springAppContext = new ClassPathXmlApplicationContext(new String[] { "testContext.xml" });
		headerService = (IHeaderService) springAppContext.getBean("headerService");
		newsGroupService = (INewsGroupService) springAppContext.getBean("newsGroupService");
		springAppContext.registerShutdownHook();
	}

}
